package com.jinly.ryder.ssh.command;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import com.jinly.ryder.ssh.command.model.LogLine;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class SedCommand {
    private Session sshSession;

    public SedCommand(Session sshSession) {
        this.sshSession = sshSession;
    }

    public List<LogLine> exec(String fileName, Long beginNum, Long endNum) {
        ChannelExec channelExec = null;
        BufferedReader input = null;
        List<LogLine> list = new ArrayList<>();
        try {
            channelExec = (ChannelExec) sshSession.openChannel("exec");
            String command = "sed -n '" + beginNum + "," + endNum + "p' " + fileName;
            log.info(command);
            channelExec.setCommand(command);
            channelExec.connect();
            input = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                LogLine logLine = new LogLine();
                logLine.setFileName(fileName);
                logLine.setText(line);
                list.add(logLine);
            }
        } catch (Exception e) {
            log.error("sed  err:{}", e.getMessage());
        } finally {
            try {
                if (input != null) input.close();
                if (channelExec != null) channelExec.disconnect();
            } catch (Exception e) {
            }
        }
        return list;
    }

}

